package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;

import java.lang.reflect.*;
import java.util.List;

/**
 *
 * @author Administrator
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <T> List<T> selectList(String statementId, Object... params) throws Exception {
        // 将要去完成对simpleExecutor里的query方法的调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        List<T> result = simpleExecutor.query(configuration, configuration.getMapperdStatementMap().get(statementId), params);
        return result;
    }

    /**
     * selectOne 对selectList进行了复用
     * @param statementId
     * @param params
     * @return
     */
    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<T> list = selectList(statementId, params);
        if (list.size() == 1) {
            return list.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者返回结果过多");
        }
    }

    @Override
    public int update(String statementId, Object... params) throws Exception {
        // 将要去完成对simpleExecutor里的query方法的调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        int result = simpleExecutor.doUpdate(configuration, configuration.getMapperdStatementMap().get(statementId), params);
        return result;
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        // 使用JDK动态代理，来为DAO接口生成代理对象，并返回
        // proxy 当前代理对象的引用  method 当前被调用方法的引用  args 当前被调用方法传递的参数
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, (proxy, method, args) -> {
            //底层还是去执行JDBC代码
            //根据不同情况，去调用selectList或者SelectOne，来执行sql语句

            //准备参数1：statementId，规定mapper中的namespace和statementname与接口和接口方法对应
            String className = method.getDeclaringClass().getName();
            String methodName = method.getName();
            String statementId = className + "." + methodName;
            //准备参数2：params，获取被调用方法的返回类型
            Type genericReturnType = method.getGenericReturnType();


            //判断当前类型是否是泛型
            if (genericReturnType instanceof ParameterizedType) {
                return selectList(statementId, args);
            } else if (genericReturnType == Integer.TYPE) {
                return update(statementId, args);
            }
            return selectOne(statementId, args);
        });
        return (T) proxyInstance;
    }

}
